package com.haibara.codesubmiteval.controller;

import com.haibara.codesubmiteval.annotation.AuthCheck;
import com.haibara.codesubmiteval.common.BaseResponse;
import com.haibara.codesubmiteval.constant.AuthConstant;
import com.haibara.codesubmiteval.constant.FileConstant;
import com.haibara.codesubmiteval.utils.FileUtil;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

/**
 * 文件控制器
 *
 * @author 大蠢驴
 * @since 2023/08/03
 */
@RestController
@RequestMapping("/file")
public class FileController {
    private final ResourceLoader resourceLoader;

    public FileController(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    /**
     * 上传文件到临时路径
     *
     * @param file 文件
     * @return 文件名
     */
    @PostMapping("/upload")
    @AuthCheck(mustRole = AuthConstant.ADMIN)
    public BaseResponse<String> upload(@RequestPart("file") MultipartFile file) {
        // 1. 创建随机文件名
        String randomFileName = FileUtil.generateRandomFileName(file.getOriginalFilename());
        // 2. 将文件放入到临时文件夹
        try {
            FileUtil.moveFileTo(file, FileConstant.tempFilePath, randomFileName);
        } catch (IOException e) {
            throw new RuntimeException("文件上传失败 : " + e.getMessage());
        }
        return BaseResponse.success(randomFileName);
    }

    /**
     * 下载模板文件
     *
     * @return 模板文件
     * @throws IOException IO异常
     */
    @GetMapping("/download")
    @AuthCheck(mustRole = AuthConstant.ADMIN)
    public ResponseEntity<InputStreamResource> getExampleFile() throws IOException {
        // 读取文件
        Resource resource = resourceLoader.getResource("classpath:example.txt");

        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=example.txt");
        headers.setContentType(MediaType.TEXT_PLAIN);

        // 返回文件
        InputStream inputStream = resource.getInputStream();
        return ResponseEntity.ok()
                .headers(headers)
                .body(new InputStreamResource(inputStream));
    }
}
